package com.application.module.couponget;

import com.application.common.Constant;
import com.application.intercept.BaseInterceptor;
import com.application.model.Global;
import com.application.module.sign.Sign;
import com.jfinal.aop.Invocation;
import com.platform.mvc.user.User;

import java.util.List;

public class LoginCouponGetInterceptor extends BaseInterceptor {


    @Override
    protected void handler(Invocation invoc) {

    }

    @Override
    protected void success(User user) {

        Global.Code code = Global.Code.gift_login;
        Global.Code code2 = Global.Code.gift_loginPlay;
        if (Constant.group_vip.equalsIgnoreCase(user.getRoleId())) {
            code = Global.Code.gift_vipLogin;
            code2 = Global.Code.gift_vipLoginPlay;
        }
        setData(user.getId(), code);
        setData(user.getId(), code2);
    }

    private void setData(int userId, Global.Code code) {
        String[] val = Global.cacheGetByCode(code).getValue().split("/");

        List<Sign> list = Sign.dao.findAvailableList(userId);

        int need = Integer.parseInt(val[0]);
        int gift = val.length > 1 ? Integer.parseInt(val[1]) : 0;

        if (list.size() >= need && gift >0) {
            list.forEach(o -> {
                o.setUsed(1);
                o.update();
            });
            CouponGet.dao.add(CouponGet.SOURCE_LOGIN, CouponGet.TYPE_UNLOCK, gift, userId);
        }
    }
}
